package mo.leetcode_top;

import java.util.HashMap;
import java.util.Map;

public class L166 {

    public String fractionToDecimal(int numerator, int denominator) {
        long a = numerator;
        long b = denominator;
        if (a % b == 0) {
            return String.valueOf(a / b);
        }
        StringBuilder start = new StringBuilder();
        if ((a > 0 && b < 0) || (a < 0 && b > 0)) {
            start.append("-");
        }
        a = Math.abs(a);
        b = Math.abs(b);

        start.append(String.valueOf(a / b)).append(".");

        a %= b;

        Map<Long, Integer> values = new HashMap<>();
        while (a != 0) {
            //将上一次计算的余数加到Set中
            values.put(a, start.length());
            a *= 10;
            start.append(a / b);
            a %= b;
            if (values.containsKey(a)) {
                int index = values.get(a);
                return start.substring(0, index) + "(" + start.substring(index, start.length())+")";
            }
        }

        return start.toString();
    }

    public static void main(String[] args) {
        L166 test = new L166();
        System.out.println(test.fractionToDecimal(1, 6));
    }

}
